package config

import (
	"strings"

	"github.com/spf13/viper"
)

type Config struct {
	App      AppConfig      `mapstructure:"app"`
	Server   ServerConfig   `mapstructure:"server"`
	Database DatabaseConfig `mapstructure:"database"`
	JWT      JWTConfig      `mapstructure:"jwt"`
	AI       AIConfig       `mapstructure:"ai"`
	Log      LogConfig      `mapstructure:"log"`
}

type AppConfig struct {
	Name    string `mapstructure:"name"`
	Mode    string `mapstructure:"mode"`
	Version string `mapstructure:"version"`
}

type ServerConfig struct {
	Port         int `mapstructure:"port"`
	ReadTimeout  int `mapstructure:"read_timeout"`
	WriteTimeout int `mapstructure:"write_timeout"`
}

type DatabaseConfig struct {
	MySQL MySQLConfig `mapstructure:"mysql"`
	Redis RedisConfig `mapstructure:"redis"`
}

type MySQLConfig struct {
	Host            string `mapstructure:"host"`
	Port            int    `mapstructure:"port"`
	Username        string `mapstructure:"username"`
	Password        string `mapstructure:"password"`
	DBName          string `mapstructure:"dbname"`
	Charset         string `mapstructure:"charset"`
	MaxIdleConns    int    `mapstructure:"max_idle_conns"`
	MaxOpenConns    int    `mapstructure:"max_open_conns"`
	ConnMaxLifetime int    `mapstructure:"conn_max_lifetime"`
}

type RedisConfig struct {
	Host     string `mapstructure:"host"`
	Port     int    `mapstructure:"port"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
}

type JWTConfig struct {
	Secret     string `mapstructure:"secret"`
	ExpireTime int    `mapstructure:"expire_time"`
}

type AIConfig struct {
	ARKAPIKEY string `mapstructure:"ARK_API_KEY"`
	MODEL     string `mapstructure:"MODEL"`
	EMBEDDER  string `mapstructure:"EMBEDDER"`
}

type LogConfig struct {
	Level        string `mapstructure:"level"`
	FileName     string `mapstructure:"file_name"`
	MaxSize      int    `mapstructure:"max_size"`
	MaxAge       int    `mapstructure:"max_age"`
	MaxBackups   int    `mapstructure:"max_backups"`
	Compress     bool   `mapstructure:"compress"`
	LogInConsole bool   `mapstructure:"log_in_console"`
	LogFormat    string `mapstructure:"log_format"`
	LogEncoding  string `mapstructure:"log_encoding"`
}

func Init() *Config {
	// 设置配置文件名称和类型
	viper.SetConfigName("config")
	viper.SetConfigType("yml")

	// 配置文件搜索路径
	viper.AddConfigPath("./config")
	viper.AddConfigPath("../config")
	viper.AddConfigPath("../../config")

	// 读取配置文件
	if err := viper.ReadInConfig(); err != nil {
		panic("Failed to read config: " + err.Error())
	}

	// 支持环境变量覆盖
	viper.AutomaticEnv()
	viper.SetEnvPrefix("APP")
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

	// 绑定环境变量到配置项
	bindEnvVars()

	var config Config
	if err := viper.Unmarshal(&config); err != nil {
		panic("Failed to unmarshal config: " + err.Error())
	}

	return &config
}

// bindEnvVars 绑定环境变量到配置项
func bindEnvVars() {
	// 应用配置
	viper.BindEnv("app.mode", "APP_MODE")
	viper.BindEnv("app.version", "APP_VERSION")

	// 服务器配置
	viper.BindEnv("server.port", "SERVER_PORT")

	// 数据库配置
	viper.BindEnv("database.mysql.host", "DB_HOST")
	viper.BindEnv("database.mysql.port", "DB_PORT")
	viper.BindEnv("database.mysql.username", "DB_USERNAME")
	viper.BindEnv("database.mysql.password", "DB_PASSWORD")
	viper.BindEnv("database.mysql.dbname", "DB_NAME")

	viper.BindEnv("database.redis.host", "REDIS_HOST")
	viper.BindEnv("database.redis.port", "REDIS_PORT")
	viper.BindEnv("database.redis.password", "REDIS_PASSWORD")
	viper.BindEnv("database.redis.db", "REDIS_DB")

	// JWT配置
	viper.BindEnv("jwt.secret", "JWT_SECRET")
	viper.BindEnv("jwt.expire_time", "JWT_EXPIRE_TIME")

	// AI配置
	viper.BindEnv("ai.ARK_API_KEY", "AI_ARK_API_KEY")
	viper.BindEnv("ai.MODEL", "AI_MODEL")
	viper.BindEnv("ai.EMBEDDER", "AI_EMBEDDER")

	// 日志配置
	viper.BindEnv("log.levle", "LOG_LEVEL")
	viper.BindEnv("log.file_name", "LOG_FILENAME")
}
